<?php
namespace ApolloClient\Console;

use ApolloClient\ApolloClientService;
use Illuminate\Console\Command;

class ApolloPullConfig extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'apollo-client:pull-config
                            {--server= : 服务器地址，例如：http://baidu.com:234}
                            {--app_id= : APPID}
                            {--cluster= : 集群}
                            {--namespace= : 空间，如有多个以英文件逗号隔开，例如：boo,bar}
                            {--secret= : 密钥}
                            {--debug= : 是否为debug状态}
                            ';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '拉取阿波罗配置文件';

    /**
     * @var array
     */
    private array $_config;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $this->info('开始进行基础数据校验');
        $this->check();
        $this->info('基础数据校验完成');
        $service = new ApolloClientService($this->_config);
        $service->handle();
    }

    /**
     * @return void
     */
    public function check()
    {
        if (! $this->checkServer()) {

            dd('server是不正确的，正确示例为：http[s]://host[:port]');
        }
        if (empty($this->option('app_id'))) {

            dd('APPID不正确');
        }
        if (empty($this->option('cluster'))) {

            dd('集群不正确');
        }
        if (empty($this->option('namespace'))) {

            dd('空间不正确');
        }
        if (empty($this->option('secret'))) {

            dd('密钥不正确');
        }
        $server = $this->option('server');
        $parseServer = parse_url($server);
        $this->_config = [
            'server'    => $this->option('server'),
            'app_id'    => $this->option('app_id'),
            'cluster'   => $this->option('cluster'),
            'namespace' => $this->option('namespace'),
            'secret'    => $this->option('secret'),
            'debug'     => (bool)$this->option('debug'),
        ];
    }

    /**
     * @return bool
     */
    protected function checkServer(): bool
    {
        $server = $this->option('server');
        if (empty($server)) {

            return false;
        }
        if (false === filter_var(
            $server,
            FILTER_VALIDATE_URL,
            FILTER_FLAG_SCHEME_REQUIRED | FILTER_FLAG_HOST_REQUIRED
        )) {

            return false;
        }
        return true;
    }
}
